<template>
	<div class="detail-container">
		<van-nav-bar
			class="page-nav-bar"
			title="商品详情"
			left-arrow
			@click-left="$router.back()"
		>
			<van-icon
				slot="right"
				name="share-o"
        v-if="!isLoading && !isError"
				@click="showShare = true"
			></van-icon>
		</van-nav-bar>
    <!-------------数据正常----------------->
    <div  v-if="!isLoading && !isError">
      <van-swipe :autoplay="3000">
        <van-swipe-item v-for="(obj, index) in gallery" :key="index">
          <img :src="obj" class="gallery" />
        </van-swipe-item>
      </van-swipe>
      <!-- 商品基础信息 -->
      <van-cell-group inset>
        <div class="goodinfo">
          <div class="title">{{ product.name }}</div>
          <div class="subtitle">{{ product.subTitle }}</div>
          <div class="price">
            <span>￥ {{ product.price }}</span
            ><s>原价：￥{{ product.originalPrice }}</s>
          </div>
        </div>
      </van-cell-group>
      <!-- 品牌信息 -->
      <van-cell-group inset>
        <van-cell is-link :to="'/brand/detail?id='+brand.id">
          <div slot="title">
            <p><b>品牌名称: </b>{{ brand.name }}</p>
          </div>
          <div slot="default">共有{{ brand.productCount }}个商品</div>
          <div slot="label">
            <van-image height="30px" :src="brand.logo"></van-image>
          </div>
        </van-cell>
      </van-cell-group>
      <!-- 规格信息 -->
      <van-cell-group inset v-if="skuStockList.length">
        <van-cell is-link>
          <div slot="title">
            <b>商品规格</b>
          </div>
          <div slot="default" @click="skuShow = true">请选择</div>
        </van-cell>
      </van-cell-group>
      <!-- 商品参数 -->
      <van-cell-group inset>
        <van-cell>
          <div slot="title">
            <b>商品参数</b>
          </div>
        </van-cell>
        <van-cell
          v-for="(item, index) in attrList"
          :key="index"
          :title="item.name"
          :value="item.value"
        ></van-cell>
      </van-cell-group>
      <!-- 商品详情 -->
      <van-cell-group inset>
        <van-cell>
          <div slot="title">
            <b>商品详情</b>
          </div>
          <div slot="label">
            <div v-html="product.detailMobileHtml"></div>
          </div>
        </van-cell>
      </van-cell-group>
      <!-- 大家都在看 -->
      <div class="tuijian">
        <div class="line"></div>
        <span class="title">大家都在看</span>
        <div class="line"></div>
      </div>
      <!-- <van-grid :border="false" :column-num="2" class="goodslist">
        <van-grid-item
          v-for="obj in goodslist"
          :key="obj.id"
          class="item"
          @click="todetail(obj.id)"
        >
          <van-image class="img" :src="obj.list_pic_url" />
          <span class="gname">{{ obj.name }}</span>
          <span class="price">￥{{ obj.retail_price }}</span>
        </van-grid-item>
      </van-grid> -->
      <!-- 商品导航 -->
      <van-goods-action>
        <van-goods-action-icon icon="like" color="#1989fa" text="已收藏" v-if="isCollect" @click="clickCollection" />
        <van-goods-action-icon icon="like-o" text="收藏" v-else @click="clickCollection" />
        <van-goods-action-icon icon="cart-o" text="购物车" />
        <van-goods-action-button
          type="warning"
          @click="onAddCartClicked"
          text="加入购物车"
        />
        <van-goods-action-button
          type="danger"
          @click="onBuyClicked"
          text="立即购买"
        />
      </van-goods-action>
      <!-- 商品SKU面板 -->
      <van-sku
        ref="sku"
        v-model="skuShow"
        :sku="sku"
        :goods="goods"
        :goods-id="product.id"
        :quota="quota"
        :quota-used="quotaUsed"
        :hide-stock="sku.hide_stock"
        @buy-clicked="onBuyClicked"
        @add-cart="onAddCartClicked"
      />
      <!-- 分享面板 -->
      <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options"
      />
    </div>
    <!-------------数据加载中----------------->
    <div v-else-if="isLoading">
      <br><br>
     <van-loading size="40px" vertical>加载中...</van-loading>
    </div>
    <!-------------数据异常----------------->
    <div v-else-if="isError">
      <van-empty image="error" description="数据异常" />
    </div>
	</div>
</template>

<script>
import { getProductDetail } from '@/api/goods'
import { addCart } from '@/api/cart'
import { createHistory } from '@/api/history'
import { mapGetters } from 'vuex'
import { getProductCollectionInfo,addProductCollection,deleteProductCollection } from "@/api/collection";
export default {
	name: 'detail',
	data() {
		return {
			isLoading: false, // 数据加载中
			isError: false, // 数据异常
			gallery: [], // 轮播图
			brand: {}, // 商品品牌
			couponList: [], //  商品可用优惠券
			product: {}, // 商品信息
			productAttributeList: [], //  商品属性与参数
			productAttributeValueList: [], //  手动录入的商品属性与参数值
			productFullReductionList: [], //  商品满减价格设置
			productLadderList: [], //  商品阶梯价格设置
			skuStockList: [], // 商品的sku库存信息
			skuShow: false, // 属性弹框
			quota: 2, // 限购数量
			quotaUsed: 0, // 已经购买的数量
			showShare: false, // 分享面板
			options: [
				{ name: '微信', icon: 'wechat' },
				{ name: '微博', icon: 'weibo' },
				{ name: '复制链接', icon: 'link' },
				{ name: '分享海报', icon: 'poster' },
				{ name: '二维码', icon: 'qrcode' },
			],
      isCollect:false // 是否被收藏
		}
	},
	computed: {
		sku() {
			// 无规格
			if (this.skuStockList.length === 0) {
				return {
					tree: [],
					list: [],
					price: this.product.price, // 默认价格（单位元）
					stock_num: this.product.stock, // 商品总库存
					collection_id: this.product.id, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
					none_sku: true, // 是否无规格商品
					hide_stock: false, // 是否隐藏剩余库存
				}
			}
			// 有规格
			const arr = []
			this.skuStockList.forEach((item) => {
				item.spData = JSON.parse(item.spData)
				arr.push(...item.spData)
			})
			let treeArr = arr.map((item) => item.key)
			treeArr = Array.from(new Set(treeArr))
			treeArr = treeArr.map((item) => ({ keyName: item }))
			treeArr.forEach((item) => {
				item.valueList = Array.from(
					new Set(
						arr
							.filter((val) => val.key === item.keyName)
							.map((val) => val.value)
					)
				)
			})
			const treeData = this.productAttributeList
				.filter((val) => val.type === 0)
				.map((item, index) => {
					const valueList = treeArr.find(
						(val) => val.keyName === item.name
					).valueList
					return {
						k: item.name, // skuKeyName：规格类目名称
						k_s: item.name, // skuKeyStr:
						v: valueList.map((keyName) => {
							return {
								id: keyName,
								name: keyName,
								imgUrl: '',
								previewImgUrl: '',
							}
						}),
					}
				})
			const listData = this.skuStockList.map((item) => {
				let obj = {
					id: item.id,
					skuCode: item.skuCode,
					price: item.price,
					stock_num: item.stock,
					str_val_desc: [],
				}
				item.spData.forEach((val) => {
					obj[val.key] = val.value
					obj.str_val_desc.push(val.value)
				})
				obj.str_val_desc = obj.str_val_desc.join('-')
				return obj
			})
			return {
				tree: treeData,
				list: listData,
				price: this.product.price, // 默认价格（单位元）
				stock_num: this.product.stock, // 商品总库存
				collection_id: this.product.id, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
				none_sku: false, // 是否无规格商品
				hide_stock: false, // 是否隐藏剩余库存
			}
		},
		goods() {
			return { picture: this.product.pic }
		},
		attrList() {
			return this.productAttributeList
				.filter((val) => val.type === 1)
				.map((item) => {
					let row = this.productAttributeValueList.find(
						(val) => val.productAttributeId === item.id
					)
					return { name: item.name, value: row.value }
				})
		},
     ...mapGetters(['username','memberId'])
	},
	created() {
		this.initData()
	},
	methods: {
    // 初始化数据
		async initData() {
			try {
				this.isLoading = true
				let res = await getProductDetail(this.$route.query.id)
				if (res.product.albumPics) this.gallery = [...res.product.albumPics.split(',')]
				if (res.product.pic) this.gallery.unshift(res.product.pic)
				if (res.product.detailMobileHtml) {
					res.product.detailMobileHtml =
						res.product.detailMobileHtml.replaceAll(
							'<img',
							'<img style="display:block;width:100%"'
						)
				}
				Object.keys(res).forEach((key) => {
					this[key] = res[key]
				})
        // 登录了，就创建浏览记录
        if(this.memberId) this.createHistory()
        // 登录了，判断是否收藏了
        if(this.memberId) this.getCollectionInfo(this.product.id)
			} catch (error) {
				this.isError = true
			}
			this.isLoading = false
		},
    // 创建浏览记录
    async createHistory(){
      await createHistory({
        "memberId": this.memberId,
        "memberNickname": this.username,
        "productId": this.product.id,
        "productName":this.product.name,
        "productPic":this.product.pic,
        "productPrice": this.product.price,
        "productSubTitle":  this.product.subTitle
      })
    },
    // 判断是否收藏了
    async getCollectionInfo(productId){
      let res = await getProductCollectionInfo({productId})
      if(res) this.isCollect = true
    },
    // 商品收藏点击
    async clickCollection(){
      if(!this.memberId) return this.$toast.fail('登录之后才可收藏')
      if(this.isCollect){
        // 取消收藏
        await deleteProductCollection({productId:this.product.id})
        this.$toast.success('取消成功')
      }else{
        // 添加收藏
        await addProductCollection({
          "memberId": this.memberId,
          "memberNickname": this.username,
          "productId": this.product.id,
          "productName":this.product.name,
          "productPic":this.product.pic,
          "productPrice": this.product.price,
          "productSubTitle":  this.product.subTitle
        })
        this.$toast.success('收藏成功')
      }
      // 视图更新
      this.isCollect = !this.isCollect
    },
		// 购买按钮点击
		onBuyClicked() {
			const skuData = this.$refs.sku.getSkuData()
			if (!skuData.selectedSkuComb && !this.skuShow)
				return (this.skuShow = true)
			console.log(skuData)
		},
		// 加入购物车
		async onAddCartClicked() {
			const skuData = this.$refs.sku.getSkuData()
			if (!skuData.selectedSkuComb && !this.skuShow)  return (this.skuShow = true)
      let productAttr,price,productSkuId,productSkuCode,quantity=1
      if(this.skuStockList.length){
        const row = this.skuStockList.find(item=>item.skuCode === skuData.selectedSkuComb.skuCode)
        productAttr = JSON.stringify(row.spData)
        price = row.price
        productSkuCode = skuData.skuCode
        quantity =  skuData.selectedNum
        productSkuId = row.id
      }else{
        price = this.product.price
        productAttr = JSON.stringify([])
        productSkuCode = ''
        productSkuId = ''
      }
      let data = {
        memberId: this.memberId,  //会员ID
        memberNickname: this.username, // 会员昵称
        price,
        productAttr,  // 商品销售属性 如[{'key':'颜色','value':'颜色'},{'key':'容量','value':'4G'}]
        productBrand: this.product.brandName,  // 商品品牌
        productCategoryId: this.product.productCategoryId, // 商品分类id 
        productId: this.product.id, // 产品id
        productName: this.product.name, // 产品名称
        productPic: this.product.pic, // 产品图片
        productSkuCode,  // 商品sku条码
        productSkuId, //  商品sku ID 
        productSn: this.product.productSn,  // 商品货号
        productSubTitle: this.product.subTitle,  // 商品副标题（卖点）
        quantity // 购买数量
      }
      // 发送请求
      await addCart(data)
      // 跳转
      this.$router.push('/cart')
		},
	},
	watch: {
		$route: function (to, from) {
			this.initData()
			window.scrollTo({
				left: 0,
				top: 0,
			})
		},
	},
}
</script>

<style lang="less" scoped>
.infoImg {
	width: 100%;
	margin-top: 100px;
}
.detail-container {
	padding-top: 92px;
	padding-bottom: 120px;
	background-color: #fafafa;
	.van-cell-group {
		margin-bottom: 20px;
	}
	.gallery {
		max-width: 100%;
	}
	.service {
		box-sizing: border-box;
		height: 36.5px;
		background: #f4f4f4;
		padding: 40px 40px;
		display: flex;
		flex-flow: row nowrap;
		align-items: center;
		justify-content: space-between;
		.item {
			background: url(~@/assets/圆点.png) 0 center no-repeat;
			background-size: 8px;
			padding-left: 15px;
			font-size: 12.5px;
			line-height: 12.5px;
			color: #666;
		}
	}
	.goodinfo {
		margin: 10px;
		border-bottom: 1px solid #ededed;
		text-align: center;
		.title {
			margin-top: 20px;
			font-size: 32px;
		}
		.subtitle {
			margin-top: 10px;
			font-size: 20px;
			color: #999;
		}
		.price {
			margin-top: 30px;
			font-size: 40px;
			color: #e11c34;
			s {
				color: #aaa;
				font-size: 20px;
				margin-left: 10px;
			}
		}
	}
	.section {
		margin-top: 20px;
		font-size: 32px;
		padding: 0px 20px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.attribute {
		margin-top: 100px;
		padding: 0 20px;
		.title {
			font-size: 32px;
		}
		.item {
			white-space: nowrap;
			font-size: 36px;
			overflow: hidden;
			text-overflow: ellipsis;
			margin-top: 20px;
			padding: 10px 0px;
			background-color: #f3f3f3;
			.name {
				display: inline-block;
				font-size: 26px;
				width: 150px;
				color: #999;
			}
			.value {
				font-size: 26px;
			}
		}
	}
	.common-problem {
		.h {
			display: flex;
			justify-content: center;
			align-items: center;
			.title {
				font-size: 34px;
				padding: 0 20px;
			}
			.line {
				height: 3px;
				width: 80px;
				background-color: #ccc;
			}
		}
		.b {
			height: auto;
			margin-top: 30px;
			overflow: hidden;
			padding: 0 40px;
			background: #fff;
			.item {
				margin-top: 20px;
			}
		}
		.question-box {
			height: 50px;
			.spot {
				float: left;
				display: block;
				height: 8px;
				width: 8px;
				background: #b4282d;
				border-radius: 50%;
				margin-top: 11px;
			}
			.question {
				float: left;
				line-height: 30px;
				padding-left: 10px;
				display: block;
				font-size: 26px;
				padding-bottom: 15px;
				color: #303030;
			}
		}
		.answer {
			line-height: 36px;
			padding-left: 16px;
			font-size: 26px;
			color: #787878;
		}
	}
	.goumai {
		display: block;
		border: 1px solid #e11c34;
	}
	.page-nav-bar {
		position: fixed;
		width: 100%;
		top: 0;
		left: 0;
	}
	.tuijian {
		margin-top: 100px;
		margin-bottom: 40px;
		display: flex;
		justify-content: center;
		align-items: center;
		.title {
			font-size: 34px;
			padding: 0 20px;
		}
		.line {
			height: 3px;
			width: 80px;
			background-color: #ccc;
		}
	}
	.goodslist {
		.item {
			text-align: center;
			.img {
				width: 300px;
				height: 300px;
			}
			.gname {
				font-size: 24px;
			}
			.price {
				margin-top: 20px;
				color: #e11c34;
				font-size: 28px;
			}
		}
	}
	.nocol {
		color: #fff;
	}
}
</style>
